package com.thinvent.recommend.manager.config;

import com.thinvent.recommend.manager.lucene.JiebaAnalyzer;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Configuration
public class LuceneConfig {

    @Bean
    public Analyzer jiebaAnalyzer() {
        // Lucene 版 Jieba 分词器
        return new JiebaAnalyzer();
    }

    @Bean
    public Directory luceneDirectory() throws Exception {
        // 尝试把索引放到 classpath 的 resources/lucene/index 下
        URL rootUrl = Thread.currentThread()
                .getContextClassLoader()
                .getResource("");
        Path basePath;
        if (rootUrl != null && "file".equals(rootUrl.getProtocol())) {
            // IDE／exploded jar 运行时，classes 可写
            basePath = Paths.get(rootUrl.toURI());
        } else {
            // 打包成 fat-jar 时，resources 在 jar 内不可写，退回到项目外部目录
            basePath = Paths.get(System.getProperty("user.dir"))
                    .resolve("data/resources");
        }

        Path indexPath = basePath.resolve("lucene/index");
        Files.createDirectories(indexPath);
        return FSDirectory.open(indexPath);
    }
}
